package mmq.mina.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import com.google.protobuf.CodedOutputStream;
import com.google.protobuf.Message;

public class ProtobufEncoder extends ProtocolEncoderAdapter {

	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		Message msg = (Message) message;
		int size = msg.getSerializedSize();
		int lenght = CodedOutputStream.computeRawVarint32Size(size);
		IoBuffer buffer = IoBuffer.allocate(lenght + size);
		CodedOutputStream cos = CodedOutputStream.newInstance(buffer.asOutputStream());
		cos.writeRawVarint32(size);
		msg.writeTo(cos);
		cos.flush();
		buffer.flip();
		out.write(buffer);
	}

}